package com.acmen.easyapi.builder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.acmen.easyapi.util.StringUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author acmen
 * 数据构建器抽象类
 */
public abstract class ApiDataBuilder {

    public JSON buildData(Type type) {
        JSON object = (JSON)buildData(type, new HashMap<>(), null);
        return object;
    }
    /**
     * 从class类型中构造模拟数据
     *
     * @param type
     * @return
     */
    protected Object buildData(Type type, Map<TypeVariable, Type> typeMap, Object example) {
        if (type instanceof WildcardType) {
            WildcardType wildcardType = (WildcardType) type;
            Type[] upperBounds = wildcardType.getUpperBounds();
            if (upperBounds.length > 0) {
                return buildData(upperBounds[0], typeMap, example);
            } else {
                Type[] lowerBounds = wildcardType.getLowerBounds();
                return buildData(lowerBounds[0], typeMap, example);
            }
        } else if (type instanceof TypeVariable) {
            Type type_ = getTargetType(type, typeMap);
            if (type_ == null) {
                return null;
            }
            return buildData(type_, typeMap, example);
        } else {
            Class clazz = null;
            Type[] params = null;
            if (type instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                params = parameterizedType.getActualTypeArguments();
                typeMap.putAll(getTypeMap(parameterizedType));
                Type rawType = parameterizedType.getRawType();
                clazz = (Class) rawType;
            } else {
                clazz = (Class) type;
            }
            if (Collection.class.isAssignableFrom(clazz)) {
                if (StringUtil.isNotEmpty(example)) {
                    return JSON.parseArray(example.toString());
                } else if (params != null && params.length > 0) {
                    JSONArray array = new JSONArray();
                    Object object1 = buildData(params[0], typeMap, null);
                    if (object1 != null) {
                        if((object1 instanceof JSONObject && ((JSONObject)object1).isEmpty())||(object1 instanceof JSONArray && ((JSONArray)object1).isEmpty())){
                            return null;
                        }else{
                            Object object2 = buildData(params[0], typeMap, null);
                            array.add(object1);
                            array.add(object2);
                            return array;
                        }
                    } else {
                        return null;
                    }
                }
            } else if (clazz.isArray()) {
                if (StringUtil.isNotEmpty(example)) {
                    return JSON.parseArray(example.toString());
                } else {
                    JSONArray array = new JSONArray();
                    Object object1 = buildData(clazz.getComponentType(), typeMap, null);
                    if (object1 != null) {
                        if((object1 instanceof JSONObject && ((JSONObject)object1).isEmpty())||(object1 instanceof JSONArray && ((JSONArray)object1).isEmpty())){
                            return null;
                        }else{
                            Object object2 = buildData(clazz.getComponentType(), typeMap, null);
                            array.add(object1);
                            array.add(object2);
                            return array;
                        }
                    } else {
                        return null;
                    }
                }
            } else if (clazz.isEnum()) {
                if (StringUtil.isNotEmpty(example)) {
                    return example;
                } else {
                    if (clazz.getEnumConstants().length > 0) {
                        return clazz.getEnumConstants()[0];
                    } else {
                        return "";
                    }
                }
            } else if (clazz.equals(LocalDateTime.class)) {
                if (StringUtil.isNotEmpty(example)) {
                    return example;
                } else {
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    return dtf.format(LocalDateTime.now());
                }
            } else if (clazz.equals(LocalDate.class)) {
                if (StringUtil.isNotEmpty(example)) {
                    return example;
                } else {
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    return dtf.format(LocalDateTime.now());
                }
            } else if (clazz.equals(LocalTime.class)) {
                if (StringUtil.isNotEmpty(example)) {
                    return example;
                } else {
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss");
                    return dtf.format(LocalDateTime.now());
                }
            } else if (clazz.equals(Date.class)) {
                if (StringUtil.isNotEmpty(example)) {
                    return example;
                } else {
                    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    return dtf.format(LocalDateTime.now());
                }
            } else if (BigDecimal.class.isAssignableFrom(clazz)
                    || Float.class.isAssignableFrom(clazz) || Double.class.isAssignableFrom(clazz)
                    || clazz.getName().equals("double") || clazz.getName().equals("float")) {
                try {
                    if (StringUtil.isNotEmpty(example)) {
                        return Double.parseDouble(example.toString());
                    } else {
                        return new Random().nextInt(100);
                    }
                } catch (Exception e) {
                    return new Random().nextInt(100);
                }
            } else if (Long.class.isAssignableFrom(clazz)
                    || clazz.getName().equals("long")) {
                try {
                    if (StringUtil.isNotEmpty(example)) {
                        return Long.parseLong(example.toString());
                    } else {
                        Random random = new Random();
                        Long l = random.nextLong()/100;
                        return l>0?l:-l;
                    }
                } catch (Exception e) {
                    Random random = new Random();
                    Long l = random.nextLong()/100;
                    return l>0?l:-l;
                }
            } else if (Integer.class.isAssignableFrom(clazz)
                    || Short.class.isAssignableFrom(clazz)
                    || clazz.getName().equals("int")
                    || clazz.getName().equals("short")) {
                try {
                    if (StringUtil.isNotEmpty(example)) {
                        return Long.parseLong(example.toString());
                    } else {
                        return new Random().nextInt(100);
                    }
                } catch (Exception e) {
                    return new Random().nextInt(100);
                }
            } else if (Boolean.class.isAssignableFrom(clazz) || clazz.getName().equals("boolean")) {
                return new Random().nextBoolean();
            } else if (clazz.equals(String.class)) {
                if (example == null) {
                    return "Abc123";
                }
                return example;
            }else if (clazz.equals(Object.class)) {
                if (example == null) {
                    return "";
                }
                return example;
            } else {
                return classToJson(clazz, typeMap);
            }
        }
        return null;
    }

    /**
     * 获取模板参数对应的类型
     *
     * @param type
     * @param typeMap
     * @return
     */

    protected Type getTargetType(Type type, Map<TypeVariable, Type> typeMap) {
        Type type_ = typeMap.get(type);
        if (type_ == null) {
            TypeVariable typeVariable = (TypeVariable) type;
            for (Map.Entry<TypeVariable, Type> entry : typeMap.entrySet()) {
                TypeVariable typeVar = entry.getKey();
                if (typeVar.getName().equals(typeVariable.getName())) {
                    Class declaration1 = (Class) typeVar.getGenericDeclaration();
                    Class declaration2 = (Class) typeVariable.getGenericDeclaration();
                    if (declaration1.isAssignableFrom(declaration2) || declaration2.isAssignableFrom(declaration1)) {
                        type_ = entry.getValue();
                    }
                }
            }
        }
        return type_;
    }

    /**
     * 获取模板与实参的对应关系
     *
     * @param parameterizedType
     * @return
     */
    protected Map<TypeVariable, Type> getTypeMap(ParameterizedType parameterizedType) {
        Map<TypeVariable, Type> typeMap = new HashMap<>();
        Type[] types = parameterizedType.getActualTypeArguments();
        TypeVariable[] typeParameters = ((Class) parameterizedType.getRawType()).getTypeParameters();
        for (int i = 0; i < types.length; i++) {
            typeMap.put(typeParameters[i], types[i]);
        }
        return typeMap;
    }

    abstract protected JSONObject classToJson(Class classType, Map<TypeVariable, Type> typeMap);
}
